package com.bzxgc.sgwer.common.page;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SublistStudentDaoImpl implements StudentDao {
    @Override
    public Pager<Student> findStrudent(Student student, int pageNum, int pageSize) {
        List<Student> studentList = getAllStudent(student);

        Pager<Student> pager = new Pager<>(pageNum, pageSize, studentList);
        return pager;
    }

    /**
     * 模仿获取所有数据
     * @param student 查询参数
     * @return 查询结果
     */
    private List<Student> getAllStudent(Student student) {
        List<Student> result = new ArrayList<>();
        List<Object> paramList = new ArrayList<>();

        String stuName = student.getStuName();
        int gender = student.getGender();

        StringBuilder sql = new StringBuilder("select * from t_student where 1=1");

        if (stuName != null && !stuName.equals("")) {
            sql.append(" and stu_name like ?");
            paramList.add("%" + stuName + "%");
        }
        if (gender == Constant.GENDER_MALE && gender == Constant.GENDER_FEMALE) {
            sql.append(" and gender=?");
            paramList.add(gender);
        }

        JdbcUtil jdbcUtil = null;
        try {
            jdbcUtil = new JdbcUtil();
            // 获取数据库连接
            jdbcUtil.getConnection();
            List<Map<String, Object>> mapList = jdbcUtil.findResult(sql.toString(), paramList);
            if (mapList != null) {
                for (Map<String, Object> map : mapList) {
                    Student s = new Student(map);
                    result.add(s);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询所有数据异常！", e);
        } finally {
            if (jdbcUtil != null) {
                // 一定要释放资源
                jdbcUtil.releaseConn();
            }
        }
        return result;
    }
}
